﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Events;
using Autodesk.Revit.UI;
using HYView;
using ModelValidation.LongitudinalModel;

namespace ModelValidation.Commands
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdLongitudinalModelChecking : IExternalCommand
	{
		public Result Execute(ExternalCommandData cmdData, ref string msg, ElementSet elems)
		{
			FloorSelectManager.CommandName = "CmdLongitudinalModelChecking";
			CmdViewType types = (CmdViewType)115;
			if (SwitchView.SetUsableView(types, cmdData) != Autodesk.Revit.UI.Result.Succeeded)
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			if (CmdLongitudinalModelChecking._hWndRevit == null)
			{
				CmdLongitudinalModelChecking._hWndRevit = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
			}
			cmdData.Application.Application.FailuresProcessing += this.OnFailuresProcessing;
			return new LongitudinalModelCheckingController(cmdData).Checking(ref msg);
		}

		private void OnFailuresProcessing(object sender, FailuresProcessingEventArgs e)
		{
			FailuresAccessor failuresAccessor = e.GetFailuresAccessor();
			string transactionName = failuresAccessor.GetTransactionName();
			IList<FailureMessageAccessor> failureMessages = failuresAccessor.GetFailureMessages();
			if (failureMessages.Count == 0)
			{
				e.SetProcessingResult((FailureProcessingResult)0);
				return;
			}
			if (transactionName.Equals("join elemet"))
			{
				foreach (FailureMessageAccessor failureMessageAccessor in failureMessages)
				{
					failuresAccessor.ResolveFailure(failureMessageAccessor);
				}
				e.SetProcessingResult((FailureProcessingResult)1);
				return;
			}
			e.SetProcessingResult((FailureProcessingResult)0);
		}

		public static WindowHandle _hWndRevit;
	}
}
